import { Button, Input, Avatar } from 'antd'
import { SmileOutlined, DribbbleOutlined, AimOutlined, HeartOutlined, DesktopOutlined } from '@ant-design/icons';
import style from './index.module.scss'
import { useLocation } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import { Msg } from '@/modules/chat';
import { UserFriendVo } from '@/modules/friend';
import useWebSocket from '@/utils/socket'
import { User } from '@/modules/login';
// import InfiniteScroll from 'react-infinite-scroll-component';
import 'mac-scrollbar/dist/mac-scrollbar.css';
import { MacScrollbar } from 'mac-scrollbar';
export default function Chat() {
  const location = useLocation();
  const item = location.state?.item as Msg;
  const fiand = location.state?.fiand as UserFriendVo
  const user = JSON.parse(window.localStorage.getItem('user')!) as User
  const [joinList, setjoinList] = useState<Array<Msg>>([])
  const [chatList, setchatList] = useState<Array<Msg>>([])
  const [msgVlaue, setmsgValue] = useState('')
  const [isJoin, setisJoin] = useState<boolean>(false)
  useEffect(() => {
    const n = location.pathname.split('/').pop()
    console.log(n);
    if (n === "9999") {
      console.log("是群聊");

      setisJoin(true)
    } else {
      console.log("是私聊");
      setisJoin(false)
    }
  }, [location.pathname])
  const [sendMessage] = useWebSocket({
    url: `ws://localhost:8090/`,
    onOpen: () => {
      //连接成功
      console.log('WebSocket 连接成功');
    },
    onClose: () => {
      //连接关闭
      console.log('WebSocket 连接关闭');
    },
    onError: (event) => {
      //连接异常
      console.error('WebSocket 连接异常:', event);
    },
    onMessage: (messageS) => {
      // console.log(message);

      //收到消息
      const msg = JSON.parse(messageS) as Msg
      if (msg.msgType === 2) {
        //群聊消息
        msg.leftOrRight = (msg.fromId === user.id.toString() ? true : false)
        console.log(msg);
        joinList.push(msg)
        setjoinList(joinList)
        console.log(joinList);
      }
      if (msg.msgType === 1) {
        //群聊消息
        msg.leftOrRight = (msg.fromId === user.id.toString() ? true : false)
        console.log(msg);
        chatList.push(msg)
        setchatList(chatList)
        console.log(chatList);
      }

    }
  });


  const sendMsg = () => {
    if (msgVlaue === '') {
      return
    }
    console.log("被");
    console.log(fiand);
    //@ts-ignore
    sendMessage({
      type: isJoin ? 2 : 1,    //聊天中的群聊
      code: 10002,//聊天
      fromId: user.id,
      nickname: user.nickname,
      msgcontent: msgVlaue,
      toId: isJoin ? 0 : fiand.userId,
      headImg: user.headImg,
      msgType: isJoin ? 2 : 1 //群聊
    })
    // sendMessage({
    // })
    setmsgValue('')
  }



  const enter = () => {
    console.log("按下了回车");
    sendMsg()
  }

  function inputValueHandle(event: React.ChangeEvent<HTMLTextAreaElement>) {
    setmsgValue(event.target.value)
  }

  return (
    <div className={style.box}>
      {/* 头部 */}
      <div className={style.header}>
        <div className={style.headerleft}>
          <div className={style.userimgbox}>
            <div className={style.userimg}>
              {
                item ? <Avatar style={{ width: '100%', height: "100%" }} src={item ? item.headImg : ""} /> :

                  <Avatar style={{ width: '100%', height: "100%" }} src={fiand ? fiand.headImg : ""} />
              }
            </div>
          </div>
          {/* 昵称 */}
          <div className={style.nicknamebox}>
            {
              item ? <div className={style.nickname}>{item ? item.addNickname : ""}</div> : <div className={style.nickname}>{fiand ? fiand.friendName : ""}</div>
            }
            {
              item ? <div className={style.phone}>{item ? item.phone : ""}</div> : <div className={style.phone}>{fiand ? fiand.phone : ""}</div>
            }
          </div>
        </div>
        <div className={style.headeright}></div>
      </div>
      {/* 聊天内容 */}
      {/* <InfiniteScroll
        dataLength={300} //This is important field to render the next data
        next={fetchData}
        hasMore={true}
        loader={<h4>聊天栏</h4>}
      >
      </InfiniteScroll> */}
      {/* 输入框 */}
      <div className={style.data} >
        <MacScrollbar
          suppressScrollX style={{
            height: "100%",
            width: "600"
          }}>
          {
            (location.pathname.split('/').pop() === "9999" ? joinList : chatList).map(e =>
              <div key={e.msgId}>
                {

                  <div style={e.leftOrRight ? {
                    display: "flex",
                    width: "95%",
                    height: "50%",
                    flexDirection: "row-reverse",
                    // flex-direction: row-reverse

                  } : {
                    display: "flex",
                    width: "95%",
                    height: "50%",
                    justifyContent: "flex-start"

                  }}>
                    <div>

                      <Avatar size='large' style={{ margin: 10, width: '100', height: "100" }} src={e.headImg} />
                    </div>
                    <div style={e.leftOrRight ? {
                      display: "flex",
                      flexDirection: 'column',
                      // alignItems: 'center',
                      justifyContent: 'space-evenly',
                      height: "200",
                      alignItems: 'flex-end',
                      width: "60%"
                    } : {
                      display: "flex",
                      flexDirection: 'column',
                      // alignItems: 'center',
                      justifyContent: 'space-evenly',
                      height: "200",
                      alignItems: 'flex-start',
                      width: "60%"
                    }}>
                      <div
                        style={{
                          color: "green"
                        }}
                      >{e.nickname}</div>
                      <div style={e.leftOrRight ? {
                        display: "flex",
                        width: "80%",
                        height: "80%",
                        padding: 5,
                        lineHeight: 1.1,
                        backgroundColor: "#95ec69",
                        color: "#232323"
                      } : {
                        padding: 5,
                        lineHeight: 1.1,
                        display: "flex",
                        width: "80%",
                        height: "80%",
                      }}>{e.msgcontent}</div>

                    </div>
                  </div>
                }
              </div>
            )
          }
        </MacScrollbar>
      </div >
      <div className={style.chatinput}>
        <div className={style.inputheade}>
          <div className={style.icons}>
            <div className={style.iconsleft}>

              <Button className={style.icon} icon={
                <SmileOutlined style={{ fontSize: "20px" }} />}></Button>

              <Button className={style.icon} icon={
                <DribbbleOutlined style={{ fontSize: "20px" }} />}></Button>

              <Button className={style.icon} icon={
                <AimOutlined style={{ fontSize: "20px" }} />}></Button>

              <Button className={style.icon} icon={
                <HeartOutlined style={{ fontSize: "20px" }} />}></Button>


              <Button className={style.icon} icon={
                <DesktopOutlined style={{ fontSize: "20px" }} />}></Button>

            </div>

            <div className={style.iconsright}>
              <Button className={style.icon} icon={
                <DesktopOutlined style={{ fontSize: "20px" }} />}></Button>

            </div>

          </div>
        </div>

        <div className={style.smg}>
          <MacScrollbar style={{
            height: "60%"
          }}>
            <Input.TextArea
              onPressEnter={enter}
              className={style.smginput}
              // value={value}
              // onChange={(e) => setValue(e.target.value)}
              // autoSize={minRows: 2, maxRows: 6 }
              placeholder="国庆快烂死在家里了..."
              autoSize={{ minRows: 5, maxRows: 8 }}
              onChange={inputValueHandle}
              value={msgVlaue}
            ></Input.TextArea>
          </MacScrollbar>
          <div className={style.send}>

            <Button onClick={sendMsg} className={style.bt}>穿越</Button>
          </div>

        </div>

      </div>
    </div >
  )
}
